import json
import datetime
import PySimpleGUI as sg

# 读数据
def readData():
    try:
        with open("data.json", "r", encoding="utf-8") as f:
            jsonData = f.read()
            return json.loads(jsonData)
    except:
        #没有文件时直接返回一个空列表
        return []

# 写数据
def writeData(dataList):
    dataJson = json.dumps(dataList, ensure_ascii=False)
    with open("data.json", "w", encoding="utf-8") as f:
        f.write(dataJson)
        sg.popup("录入成功")

# 展示数据
def showData():
    showList = []
    dataList = readData()
    for d in dataList:
        if d["类型"] == "收入":
            formatData = [d["时间"], d["描述"], d["金额"], d["类型"]]
        else:
            formatData = [d["时间"], d["描述"], d["金额"] * -1, d["类型"]]  # 金额负数
        showList.append(formatData)
    return showList

# 返回总收入 总支出 和差额
def calTotal():
    income = 0  # 收入
    outcome = 0  # 支出
    dataList = readData()
    for d in dataList:
        if d["类型"] == "收入":
            income += d["金额"]
        else:
            outcome += d["金额"]
    return (income, outcome)


# 添加数据
def addData(description, amount, _type):
    dataList = readData()
    nowTime = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
    jsonData = {"时间":nowTime,"描述":description,"金额":amount,"类型":_type}
    dataList.append(jsonData)
    writeData(dataList)

#更新界面
def updateMenu(window,values):
    list = showData()
    (income, outcome) = calTotal()
    balance = income - outcome
    text = f'总支出:{outcome}元\t总收出:{income}元\t结余:{balance}元,'
    window["-show-"].update(values=list)
    window["-text-"].update(value=text)
    window["-description-"].update("")
    window["-amount-"].update("")

# GUI
def main():
    #数据部分
    list = showData()
    (income, outcome) = calTotal()
    balance = income - outcome
    text = f"总支出:{outcome}元\t总收出:{income}元\t结余:{balance}元,"

    # 布局
    layout = [
        [sg.Text('账目清单')],
        [sg.Table(list, headings = ["时间","项目","金额","类型"],
            key = "-show-",
            justification = "center",
            auto_size_columns = False,
            def_col_width = 15
            )],
        [sg.Text(text, key = "-text-")],
        [sg.Text('请输入账单描述:'), sg.Input(key="-description-")],
        [sg.Text('请输入账单金额:'), sg.Input(key="-amount-")],
        [sg.Radio(i,group_id = 1, key = i,size = 5) for i in ["收入", "支出"]],
        [sg.Button('确认提交')]
    ]

    #绘制窗口
    window = sg.Window("记账本", layout)
    while True:
        event, values = window.read()
        #提交获取数据
        try: 
            if event == "确认提交":
                descrip = values["-description-"]
                amount = float(values["-amount-"])
                for k,v in values.items():
                    if v == True:
                        _type = k
                #写回json文件
                addData(descrip,amount,_type)
                #更新界面
                updateMenu(window,values)
        except:
            sg.popup("录入信息格式错误")

        if event in (None, 'NoneType'):
            break
    window.close()

main()
